package com.gitee.chenyaohua.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;

import java.io.*;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.HashMap;

public class FreemarkerUtil {

    private final static Logger logger = new ConsoleLogger();

    public static String generateJavaFile(String templateFile, String outFile, HashMap<String,Object> params){
        Configuration configuration = new Configuration();
        File docFile = new File(outFile);
        BufferedWriter out = null;
        try {
            String templateFileName = StringUtils.substringAfterLast(Paths.get(templateFile).toString(), File.separator);
            String templatePath = StringUtils.substringBeforeLast(templateFile , File.separator);

            configuration.setDirectoryForTemplateLoading(new File(templatePath));
            Template template = configuration.getTemplate(templateFileName);
            if (docFile.exists()){
                logger.warn(MessageFormat.format("outFile={0}文件已覆盖原有文件",outFile));
                if(!docFile.isFile()){
                    logger.error(MessageFormat.format("outFile={0}不是一个文件",outFile));
                    throw new FileNotFoundException();
                }
            }

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));

            template.process(params, out);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                IOUtils.close(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

}
